use utf8;

############################################################################################
#                             Définition de l'onglet Evenement                             #
############################################################################################

my $events = $blocnote->add('Évènements', -label => 'Évènements',);
$events->configure( -background => 'white',);

# Message de retour
my $messageEvent = '';

# Mise en place du titre
my $c = $events->Canvas(-width => 500, -height => 1, -background => 'white', -borderwidth => 0)->pack(-pady => 2);
$c->createLine(1,1, 500,1); 
$events->Label ( -text => "Rechercher / Ajouter un Evenement", -background => 'white')->pack();
$c = $events->Canvas(-width => 500, -height => 1, -background => 'white', -borderwidth => 0)->pack();
$c->createLine(1,1, 500,1); 

#Définition des champs de recherche
my $fieldEvents = $events->Frame(-background => 'white')->pack(-anchor => 'n', -pady => 15, -padx => 15);

$fieldEvents->Label( -text => 'Lieu:', -background => 'white', -justify => 'left')->grid(-row => 0, -column => 0, -sticky => 'w');
my $place = $fieldEvents->Entry()->grid(-row => 0, -column => 1, -sticky => 'w');

$fieldEvents->Label( -text => "Date:", -background => 'white', -justify => 'left')->grid(-row => 1, -column => 0, -sticky => 'w');
my $date = $fieldEvents->Entry()->grid(-row => 1, -column => 1, -sticky => 'w');

my $gamesList = gestion_bd::searchGame("", "", "", "", "", "");

$fieldEvents->Label( -text => 'Jeu:', -background => 'white',)->grid(-row => 2, -column => 0, -sticky => 'w',);
my $game = '';
my $menu = $fieldEvents->BrowseEntry(-listheight => 0, -variable => \$game)->grid(-row => 2, -column => 1, -sticky => 'w');

foreach my $g (sort {$gamesList->{$a}{nomJeu} cmp $gamesList->{$b}{nomJeu}} keys %{$gamesList}) {
	$menu->insert('end', $gamesList->{$g}{nomJeu});
}

my $buttonFrame = $events->Frame(-background => 'white')->pack(-anchor => 'n');

$buttonFrame->Button(-text => 'Ajouter',
                     -command => [sub{
				   	if($place->get ne '' and $date->get ne '' and $nbParticipant->get ne '' and $game ne ''){
				    	AddEvent();
                    }
                    else{
                    	$messageEvent = "Pour ajouter un evenement merci de renseigner tous les champs.";
                    }}])->grid(-row => 3, -column => 0, -pady => 5, -sticky => 'w', -padx => 7);
$buttonFrame->Button(-text => 'Rechercher', -command => [\&SearchEvent])->grid(-row => 3, -column => 1, -pady => 5, -sticky => 'w', -padx => 7);
$buttonFrame->Button(-text => 'Effacer', -command =>[\&ClearGame, $place, $date, $nbParticipant, \$game])->grid(-row => 3, -column => 2, -pady => 5, -sticky => 'w', -padx => 7);

$events->Label(-textvariable => \$messageEvent, -background => 'white')->pack();

############################################################################################
#                            Fonctions de gestion des Evenements                           #
############################################################################################

# Fonction ajoutant un evenemnt
sub AddEvent{
	my $dialog_box = $window->DialogBox(-title => 'Ajout d\'un Evenement', -buttons => ["OK"], -background => 'white');
  	gestion_bd::addEvent($place->get, $date->get, $nbParticipant->get, $game);
  	$dialog_box->Label(-text => "Evenement ajouté !", -background => 'white')->pack();
  	$dialog_box->Show();
}

# Fonction affichant le résultat de la recherche d'un evenement
sub SearchEvent{
	my $i = 1;
	my $j = 0;
	my $k = 0;
	my $dialog_box = $window->DialogBox(-title => 'Résultat de la recherche', -buttons    => ["Supprimer", "Jeux", "Modifier", "Quitter", "Commentaires", "Participants", "Participer"], -background => 'white');

	$dialog_box->Label(-text => "Lieu", -relief =>'groove',)->grid(-row => 0, -column => 1, -sticky => "nsew");
	$dialog_box->Label(-text => "Date", -relief =>'groove',)->grid(-row => 0, -column => 2, -sticky => "nsew");
	$dialog_box->Label(-text => "Nombre de Jeux", -relief =>'groove',)->grid(-row => 0, -column => 3, -sticky => "nsew");
	$dialog_box->Label(-text => "Nombre de Participants", -relief =>'groove',)->grid(-row => 0, -column => 4, -sticky => "nsew");

	my $eventsList = gestion_bd::searchEvent($place->get,$date->get,$game,"");
	my $event;
	my $gamesList;
	my $participantsList;

	foreach my $e (sort {$eventsList->{$a}{dateEvenement} cmp $eventsList->{$b}{dateEvenement}} keys %{$eventsList}) {
		$gamesList = gestion_bd::selectGame($e);

		foreach my $g (keys %{$gamesList}) {
			$j = $j + 1;
		}

		$participantsList = gestion_bd::selectParticipant($e);

		foreach my $g (keys %{$participantsList}) {
			$k = $k + 1;
		}

		$dialog_box->Radiobutton(-value=>$eventsList->{$e}{idEvenement}, -variable=>\$event)->grid(-row => $i, -column => 0,);
		$dialog_box->Label(-text => $eventsList->{$e}{lieu}, -background => 'white')->grid(-row => $i, -column => 1,);
		$dialog_box->Label(-text => gestion_bd::convertDate($eventsList->{$e}{dateEvenement}), -background => 'white')->grid(-row => $i, -column => 2,);
		$dialog_box->Label(-text => $j, -background => 'white')->grid(-row => $i, -column => 3,);
		$dialog_box->Label(-text => $k, -background => 'white')->grid(-row => $i, -column => 4,);
		$i = $i + 1;
		$j = 0;
		$k = 0;
	}

	my $reponse = $dialog_box->Show();

	if ($reponse eq "Supprimer" and defined($event)) {
		DeleteEvent($event);
	}
	elsif ($reponse eq "Commentaires" and defined($event)) {
		CommitOfEvent($event);
	}
    elsif ($reponse eq "Participants" and defined($event)) {
        ParticipantOfEvent($event);
    }
    elsif ($reponse eq "Participer" and defined($event)) {
        ParticipToEvent($event);
    }
	elsif ($reponse eq "Jeux" and defined($event)) {
		GameOfEvent($event);
	}
	elsif ($reponse eq "Modifier" and defined($event)) {
		ModifyEvent($event);
	}
	elsif ($reponse ne "Quitter") {
		errorBox("Veuillez selectionner un evenement !");
		SearchEvent();
	}
}

sub ParticipantOfEvent{
  my $i = 1;
  my $dialog_box = $window->DialogBox(-title => "Participants de l'evenement", -buttons => ["Quitter"], -background => 'white');

  $dialog_box->Label(-text => "Nom", -relief =>'groove',)->grid(-row => 0, -column => 1, -sticky => "nsew");
  $dialog_box->Label(-text => "Prénom", -relief =>'groove',)->grid(-row => 0, -column => 2, -sticky => "nsew");
  $dialog_box->Label(-text => "login", -relief =>'groove',)->grid(-row => 0, -column => 3, -sticky => "nsew");

  my $membersList = gestion_bd::selectParticipant($_[0]);

  foreach my $m (sort {$membersList->{$a}{nomPersonne} cmp $membersList->{$b}{nomPersonne}} keys %{$membersList}) {
    $dialog_box->Label(-text => $membersList->{$m}{nomPersonne}, -background => 'white')->grid(-row => $i, -column => 1,);
    $dialog_box->Label(-text => $membersList->{$m}{prenomPersonne}, -background => 'white')->grid(-row => $i, -column => 2,);
    $dialog_box->Label(-text => $membersList->{$m}{login}, -background => 'white')->grid(-row => $i, -column => 3,);
    $i = $i + 1;
  }

  $dialog_box->Show();
}

# Fonction permettant de modifier un evenement
sub ModifyEvent {
	my $dialog_box = $window->DialogBox(-title => "Modification d'un evenement", -buttons    => ["Enregistrer", "Annuler"], -background => 'white', -default_button => 'Annuler');
	 
	my $eventsList = gestion_bd::searchEvent("", "", $_[0]);
	my $fieldEvents = $dialog_box->Frame(-background => 'white')->pack(-anchor => 'n', -pady => 15, -padx => 15);

	$fieldEvents->Label( -text => 'Lieu:', -background => 'white', -justify => 'left')->grid(-row => 0, -column => 0, -sticky => 'w');
	my $place = $fieldEvents->Entry(-textvariable => $eventsList->{$_[0]}{lieu})->grid(-row => 0, -column => 1, -sticky => 'w');

	$fieldEvents->Label( -text => "Date:", -background => 'white', -justify => 'left')->grid(-row => 1, -column => 0, -sticky => 'w');
	my $date = $fieldEvents->Entry(-textvariable => gestion_bd::convertDate($eventsList->{$_[0]}{dateEvenement}))->grid(-row => 1, -column => 1, -sticky => 'w');

    my $reponse = $dialog_box->Show();

    if ($reponse eq "Enregistrer") {
    	gestion_bd::updateEvent($_[0],$date->get,$place->get);
    	dialogBox("Information","Modification enregistrée !");
  	}
}

#Fonction supprimant un evenement
sub DeleteEvent {
  my $dialog_box = $window->DialogBox(-title  => 'Suppression d\'un Evenement', -buttons => ["OK"], -background => 'white');
  gestion_bd::deleteEvent($_[0]);
  $dialog_box->Label(-text => "Evenement supprimé !", -background => 'white')->pack();
  $dialog_box->Show();
}

#Fonction supprimant un evenement
sub CommitEvent {
	my $dialog_box = $window->DialogBox(-title => "Commentaire d'un Evenement", -buttons    => ["Enregistrer", "Annuler"], -background => 'white', -default_button => 'Annuler');

	my $fieldEvents = $dialog_box->Frame(-background => 'white')->pack(-anchor => 'n', -pady => 15, -padx => 15);

	$fieldEvents->Label(-text => "Login:", -background => 'white', -justify => 'left')->grid(-row => 0, -column => 0, -sticky => 'w');
	my $login = $fieldEvents->Entry(-width => 40)->grid(-row => 0, -column => 1,-columnspan => 3, -sticky => 'w');

	$fieldEvents->Label(-text => "Commentaire:", -background => 'white', -justify => 'left')->grid(-row => 1, -column => 0, -sticky => 'nw');
	my $com = $fieldEvents->Text(-width => 40, -height => 10)->grid(-row => 1, -column => 1,-columnspan => 3);

	my $reponse = $dialog_box->Show();

    if ($reponse eq "Enregistrer" and $login->get ne '' and $com->get('1.0', 'end') ne '') {
    	my $id = gestion_bd::getIdSubscriber($login->get);

    	if(defined($id)){
    		gestion_bd::commitEvent($_[0], $id, $com->get('1.0', 'end'));
    		dialogBox("Information","Commentaire enregistré !");
    	}
    	else{
    		errorBox("Le login ne correspond à aucun adhérent connu !");
    		CommitEvent($_[0]);
    	}
  	}
  	elsif($reponse eq "Enregistrer" and ($login->get eq '' or $com->get('1.0', 'end') eq '')){
  		errorBox("Merci de remplir tous les champs !");
  		CommitEvent($_[0]);
  	}
}

#Fonction permettant de participer à un evenement
sub ParticipToEvent {
  my $dialog_box = $window->DialogBox(-title => "Participer à un Evenement", -buttons    => ["Enregistrer", "Annuler"], -background => 'white', -default_button => 'Annuler');

  my $fieldEvents = $dialog_box->Frame(-background => 'white')->pack(-anchor => 'n', -pady => 15, -padx => 15);

  $fieldEvents->Label(-text => "Login:", -background => 'white', -justify => 'left')->grid(-row => 0, -column => 0, -sticky => 'w');
  my $login = $fieldEvents->Entry(-width => 40)->grid(-row => 0, -column => 1,-columnspan => 3, -sticky => 'w');

  my $reponse = $dialog_box->Show();

    if ($reponse eq "Enregistrer" and $login->get ne '') {
      my $id = gestion_bd::getIdSubscriber($login->get);

      if(defined($id)){
        gestion_bd::participEvent($_[0], $id);
        dialogBox("Information","Participation enregistrée !");
      }
      else{
        errorBox("Le login ne correspond à aucun adhérent connu !");
        ParticipToEvent($_[0]);
      }
    }
    elsif($reponse eq "Enregistrer" and $login->get eq ''){
      errorBox("Merci de remplir tous les champs !");
      ParticipToEvent($_[0]);
    }
}

# Fonction affichant les jeux pour un evement donné (idEvenement)
sub GameOfEvent{
  my $i = 1;
  my $dialog_box = $window->DialogBox(-title => 'Liste des Jeux', -buttons => ["Noter", "Modifier", "Supprimer", "Ajouter", "Quitter"], -background => 'white');

  $dialog_box->Label(-text => "Nom", -relief =>'groove',)->grid(-row => 0, -column => 1, -sticky => "nsew");
  $dialog_box->Label(-text => "Nombre de joueurs", -relief =>'groove',)->grid(-row => 0, -column => 2, -sticky => "nsew");
  $dialog_box->Label(-text => "Date d'achat", -relief =>'groove',)->grid(-row => 0, -column => 3, -sticky => "nsew");
  $dialog_box->Label(-text => "Prix d'achat", -relief =>'groove',)->grid(-row => 0, -column => 4, -sticky => "nsew");
  $dialog_box->Label(-text => "Etat", -relief =>'groove',)->grid(-row => 0, -column => 5, -sticky => "nsew");

  my $gamesList = gestion_bd::selectGame($_[0]);
  my $game;

  foreach my $g (sort {$gamesList->{$a}{nomJeu} cmp $gamesList->{$b}{nomJeu}} keys %{$gamesList}) {
    $dialog_box->Radiobutton(-value=>$gamesList->{$g}{nomJeu}, -variable=>\$game)->grid(-row => $i, -column => 0,);
    $dialog_box->Label(-text => $gamesList->{$g}{nomJeu}, -background => 'white')->grid(-row => $i, -column => 1,);
    $dialog_box->Label(-text => "$gamesList->{$g}{joueursMin}-$gamesList->{$g}{joueursMax}", -background => 'white')->grid(-row => $i, -column => 2,);
    $dialog_box->Label(-text => gestion_bd::convertDate($gamesList->{$g}{dateAchat}), -background => 'white')->grid(-row => $i, -column => 3,);
    $dialog_box->Label(-text => $gamesList->{$g}{prixAchat}.'€', -background => 'white')->grid(-row => $i, -column => 4,);
    $dialog_box->Label(-text => $gamesList->{$g}{etat}, -background => 'white')->grid(-row => $i, -column => 5,);
    $i = $i + 1;
  }

  my $reponse = $dialog_box->Show();
  
  if ($reponse eq "Modifier" and defined($game)) {
    ModifyGame($game);
  }
  elsif ($reponse eq "Ajouter") {
    AddGameToEvent($_[0]);
  }
  elsif ($reponse eq "Supprimer" and defined($game)) {
    DeleteGameFromEvent($game,$_[0]);#À supprimer uniquement de l'evenement
  }
  elsif ($reponse eq "Noter" and defined($game)) {
    MarkGame($game);
  }
  elsif ($reponse eq "Modifier" or $reponse eq "Supprimer" or $reponse eq "Noter") {
    errorBox("Veuillez selectionner un jeu !");
    GameOfEvent();
  }
}

sub AddGameToEvent {
  my $dialog_box = $window->DialogBox(-title => "Ajouter un jeu à un Evenement", -buttons    => ["Ajouter", "Annuler"], -background => 'white', -default_button => 'Annuler');

  my $fieldEvents = $dialog_box->Frame(-background => 'white')->pack(-anchor => 'n', -pady => 15, -padx => 15);

  $fieldEvents->Label( -text => 'Jeu:', -background => 'white',)->grid(-row => 2, -column => 0, -sticky => 'w',);
  my $game = '';
  my $menu = $fieldEvents->BrowseEntry(-listheight => 0, -variable => \$game)->grid(-row => 2, -column => 1, -sticky => 'w');

  foreach my $g (sort {$gamesList->{$a}{nomJeu} cmp $gamesList->{$b}{nomJeu}} keys %{$gamesList}) {
    my $id = gestion_bd::getGameOfEvent($_[0],$gamesList->{$g}{nomJeu});
    if(!defined($id)){
      $menu->insert('end', $gamesList->{$g}{nomJeu});
    }
  }

  my $reponse = $dialog_box->Show();

    if ($reponse eq "Ajouter" and $game ne '') {
        gestion_bd::addGameToEvent($_[0], $game);
        dialogBox("Information","Jeu ajouté à l'évenement !");
    }
    elsif($reponse eq "Ajouter" and $game eq ''){
      errorBox("Merci de selectionner un jeu !");
      AddGameToEvent($_[0]);
    }
}

sub CommitOfEvent{
  my $i = 1;
  my $dialog_box = $window->DialogBox(-title => 'Liste des Commentaires', -buttons => ["Ajouter", "Quitter"], -background => 'white');

  $dialog_box->Label(-text => "Login", -relief =>'groove',)->grid(-row => 0, -column => 1, -sticky => "nsew");
  $dialog_box->Label(-text => "Commentaire", -relief =>'groove',)->grid(-row => 0, -column => 2, -sticky => "nsew");

  my $membersList = gestion_bd::selectCommit($_[0]);
  my $member;

  foreach my $m (sort {$membersList->{$a}{login} cmp $membersList->{$b}{login}} keys %{$membersList}) {
    $dialog_box->Label(-text => $membersList->{$m}{login}, -background => 'white')->grid(-row => $i, -column => 1,);
    $dialog_box->Label(-text => $membersList->{$m}{commentaire}, -background => 'white')->grid(-row => $i, -column => 2,);
    $i = $i + 1;
  }

  my $reponse = $dialog_box->Show();
  
  if ($reponse eq "Ajouter") {
      CommitEvent($_[0]);
  }
}

# Fonction supprimant un jeu
sub DeleteGameFromEvent {
  my $dialog_box = $window->DialogBox(-title  => "Suppression d'un jeu d'un evenement", -buttons => ["OK"], -background => 'white');
  gestion_bd::deleteGameFromEvent($_[0],$_[1]);
  $dialog_box->Label(-text => "Jeu supprimé !", -background => 'white')->pack();
  $dialog_box->Show();
}